// (Math: approximate the square root) There are several techniques for implementing the sqrt method in the Math class. One such technique is known as the 
// Babylonian method. It approximates the square root of a number, n, by repeatedly 
// performing a calculation using the following formula:
// nextGuess = (lastGuess + n / lastGuess) / 2
// When nextGuess and lastGuess are almost identical, nextGuess is the 
// approximated square root. The initial guess can be any positive value (e.g., 1).
// This value will be the starting value for lastGuess. If the difference between 
// nextGuess and lastGuess is less than a very small number, such as 0.0001,
// you can claim that nextGuess is the approximated square root of n. If not, nextGuess becomes lastGuess and the approximation process continues. Implement the following method that returns the square root of n.

import java.util.Scanner;

public class test622 {

    public static double sqrt(double n) {
        // 处理特殊情况
        if (n < 0) {
            return Double.NaN; // 负数返回NaN
        }
        if (n == 0) {
            return 0.0; // 0的平方根是0
        }
        
        double lastGuess = n; // 初始猜测值
        double nextGuess = (lastGuess + n / lastGuess) / 2;
        final double PRECISION = 0.0001; // 精度要求
        
        // 迭代计算直到满足精度要求
        while (Math.abs(nextGuess - lastGuess) > PRECISION) {
            lastGuess = nextGuess;
            nextGuess = (lastGuess + n / lastGuess) / 2;
        }
        
        return nextGuess;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("请输入一个需要计算平方根的数字: ");
        double number = scanner.nextDouble();
        
        double result = sqrt(number);
        
        if (Double.isNaN(result)) {
            System.out.println("错误：不能计算负数的平方根！");
        } else {
            System.out.printf("数字 %.2f 的平方根是: %.6f%n", number, result);
        }
        
        scanner.close();
    }
}